<template>
	<data-table-item-wrapper :designer="designer" :field="thisField" :rules="rules" :design-state="thisDesignState"
					   :parent-widget="thisParentWidget" :parent-list="thisParentList" :index-of-parent-list="thisIndexOfParentList" :style="field.options.customStyle"
					   :sub-form-row-index="thisSubFormRowIndex" :sub-form-col-index="thisSubFormColIndex" :sub-form-row-id="thisSubFormRowId">
		<el-main class="nopadding" :style="{width:thisField.options.tableWidth+'%',height:(thisField.options.tableHeight==''?'auto':thisField.options.tableHeight+'px')}">
			<sc-table
					  :data="thisField.options.tableData"
					  :apiObj:="apiObj"
					  @row-click="handleRowClick"
					  @cell-click="handleCellClick"
					  @header-click	="handleHeaderClick"
					  row-key="id"
					  remoteSort remoteFilter
			>
				<el-table-column v-if="thisField.options.showCheckBox" type="selection" width="50"></el-table-column>
				<el-table-column v-if="thisField.options.showIndex" label="#" type="index" width="50" fixed="left"></el-table-column>
				<template v-for="item in thisField.options.tableColumns" :key="item.prop">
					<el-table-column
						v-if="item.show"
						:prop="item.prop"
						:label="item.label"
						:width="item.width"
						:align="item.align"
						:fixed="item.fixed"
						:sortable="item.sortable"
					>
						<template #default="scope" v-if="item.formatS!=''||(item.formatS!=''&&item.render!='')">
							{{Formatter(scope.row,item)}}
						</template>
					</el-table-column>
				</template>
				<el-table-column v-if="thisField.options.showButtonsColumn" :label="thisField.options.buttonsColumnTitle"
								 fixed="right"
								 :align="thisField.options.buttonsColumnFixed"
								 :width="thisField.options.buttonsColumnWidth+`px`">
					<template #default="scope">
						<div v-for="item in thisField.options.operationButtons" :key="item.name" style="display: inline-block">
							<el-button text :type="item.type" v-if="item.hidden"
									   :size="item.size"
									   :disabled="item.disabled"
									   @click="this.doEvent(scope.row, scope.$index,item.name)">{{item.label}}</el-button>
						</div>
					</template>
				</el-table-column>
			</sc-table>
		</el-main>
	</data-table-item-wrapper>
</template>

<script>
import DataTableItemWrapper from './data-table-item-wrapper'
import emitter from '@/utils/emitter'
import fieldMixin from "@/components/designer/form-designer/form-widget/field-widget/fieldMixin";
import ScTable from "@/components/scTable";
export default {
	name: "data-table-widget",
	componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
	mixins: [emitter, fieldMixin],
	props: {
		field: Object,
		parentWidget: Object,
		parentList: Array,
		indexOfParentList: Number,
		designer: Object,
		designState: {
			type: Boolean,
			default: false
		},
		subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
			type: Number,
			default: -1
		},
		subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
			type: Number,
			default: -1
		},
		subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
			type: String,
			default: ''
		},
	},
	components: {
		ScTable,
		DataTableItemWrapper,
	},
	data() {
		return {
			thisField: this.field,
			thisParentWidget: this.parentWidget,
			thisParentList:this.parentList,
			thisIndexOfParentList:this.indexOfParentList,
			thisDesignState:this.designState,
			thisSubFormRowIndex:this.subFormRowIndex,
			thisSubFormColIndex:this.subFormColIndex,
			thisSubFormRowId:this.subFormRowId,
			oldFieldValue: null, //field组件change之前的值
			fieldModel: null,
			rules: [],
			apiObj:''
		}
	},
	computed: {
		inputType() {
			if (this.thisField.options.type === 'number') {
				return 'text'  //当input的type设置为number时，如果输入非数字字符，则v-model拿到的值为空字符串，无法实现输入校验！故屏蔽之！！
			}
			return this.thisField.options.type
		},
	},
	beforeCreate() {
		/* 这里不能访问方法和属性！！ */
	},

	created() {
		/* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
		   需要在父组件created中初始化！！ */
		this.initFieldModel()
		this.registerToRefList()
		this.initEventHandler()
		this.buildFieldRules()
		this.handleOnCreated()
	},

	mounted() {
		this.handleOnMounted()
		if(this.thisField.options.dbInterFace===''||this.thisField.options.dbInterFace===null)
		{
			this.apiObj = this.thisField.options.apiObj;
		}
	},

	beforeUnmount() {
		this.unregisterFromRefList()
	},

	methods: {
		doEvent(row,index,command){
			console.log(row);
			console.log(command);
		},
		handleRowClick(row, column, event)
		{
			if (this.field.options.onRowClick) {
				let customFn = new Function('event','row', this.field.options.onRowClick)
				customFn.call(this, event,row)
			}
		},
		handleCellClick(row, column, cell, event)
		{
			if (this.field.options.onCellClick) {
				let customFn = new Function('event','row','column', this.field.options.onCellClick)
				customFn.call(this, event,row,column)
			}
		},
		handleHeaderClick(column,event)
		{
			if (this.field.options.onHeaderClick) {
				let customFn = new Function('event','column', this.field.options.onHeaderClick)
				customFn.call(this, event,column)
			}
		},
		Formatter(row,item)
		{
			let fmt = item.formatS;
			let data = row[item.prop];
			let render = item.render;
			if(render!=="")
			{
				let customFn = new Function('row','item', render)
				return customFn.call(this, row,item)
			}else{
				if(fmt.indexOf("#")>=0)
				{
					return this.formatNumber(data, fmt);
				}else{
					let date = new Date(data);
					if (typeof(fmt) === "undefined") {
						fmt = "yyyy-MM-dd HH:mm:ss";
					}
					if (/(y+)/.test(fmt)) {
						fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
					}
					let o = {
						"YYYY": date.getFullYear(),
						'MM': date.getMonth() + 1,
						'DD': date.getDate(),
						'HH': date.getHours(),
						'hh': date.getHours()>12?(date.getHours()-12):date.getHours(),
						'mm': date.getMinutes(),
						'ss': date.getSeconds()
					}
					for (let k in o) {
						let str = o[k]+"";
						if(str.length===1)
						{
							str="0"+str;
						}
						fmt = fmt.replace(k,str);
					}
					return fmt
				}
			}
		},
		formatNumber(value, pattern) {
			if (value == null) return value;
			let strarr = value ? value.toString().split(".") : ["0"];
			let fmtarr = pattern ? pattern.split(".") : [""];
			let retstr = "";
			// 整数部分
			let str = strarr[0];
			let fmt = fmtarr[0];
			let i = str.length - 1;
			let comma = false;
			for (let f = fmt.length - 1; f >= 0; f--) {
				switch (fmt.substr(f, 1)) {
					case "#":
						if (i >= 0) retstr = str.substr(i--, 1) + retstr;
						break;
					case "0":
						if (i >= 0) retstr = str.substr(i--, 1) + retstr;
						else retstr = "0" + retstr;
						break;
					case ",":
						comma = true;
						retstr = "," + retstr;
						break;
				}
			}
			if (i >= 0) {
				if (comma) {
					let l = str.length;
					for (; i >= 0; i--) {
						retstr = str.substr(i, 1) + retstr;
						if (i > 0 && (l - i) % 3 == 0) retstr = "," + retstr;
					}
				} else retstr = str.substr(0, i + 1) + retstr;
			}
			retstr = retstr + ".";
			// 处理小数部分
			str = strarr.length > 1 ? strarr[1] : "";
			fmt = fmtarr.length > 1 ? fmtarr[1] : "";
			i = 0;
			for (let f = 0; f < fmt.length; f++) {
				switch (fmt.substr(f, 1)) {
					case "#":
						if (i < str.length) retstr += str.substr(i++, 1);
						break;
					case "0":
						if (i < str.length) retstr += str.substr(i++, 1);
						else retstr += "0";
						break;
				}
			}
			if(pattern.endsWith("%"))
			{
				return (retstr.replace(/^,+/, "").replace(/\.$/, ""))+"%";
			}else
			{
				return retstr.replace(/^,+/, "").replace(/\.$/, "");
			}
		}
	}
}
</script>

